package cn.yyx.customerservice.controller;


import cn.yyx.common.R;
import cn.yyx.customerservice.OssUtil;
import cn.yyx.customerservice.entity.Customer;
import cn.yyx.customerservice.entity.CustomerImg;
import cn.yyx.customerservice.service.impl.CustomerImgServiceImpl;
import cn.yyx.customerservice.service.impl.CustomerServiceImpl;
import cn.yyx.empservice.service.impl.EmployeeServiceImpl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lsj
 * @since 2023-10-25
 */
@RestController
@RequestMapping("/customer")
public class CustomerController {
    @Autowired
    private CustomerServiceImpl service;
    @Autowired
    private CustomerImgServiceImpl customerImgService;
    @Autowired
    private EmployeeServiceImpl employeeService;

    private List<String> fileList;



    /**
     * 条件分页查询
     *
     * @param page
     * @param limit
     * @param query
     * @return
     */
    @PostMapping("/{page}/{limit}")
    public R list(@PathVariable Integer page,
                  @PathVariable Integer limit,
                  @RequestBody String query) {
        QueryWrapper queryWrapper = new QueryWrapper<Customer>(new Customer());
        //将从前端取到JSON类型的条件数据转换为map
        Map map = (Map) JSON.parse(query);
        Page page1 = new Page<>(page, limit);
        //开始查询
        if (map.get("cname") != null && map.get("cname")!="") {
            queryWrapper.eq("cname", map.get("cname"));
        }
        if (map.get("saleId") != null && map.get("saleId")!="") {
            queryWrapper.eq("sale_id", map.get("saleId"));
        }
        if (map.get("operatorId") != null && map.get("operatorId")!="") {
            queryWrapper.eq("operator_id", map.get("operatorId"));
        }
        //模糊分页查询
        service.page(page1,queryWrapper);
        List<Customer> customers =page1.getRecords();
        System.out.println("customers:"+customers);
        for (Customer customer:customers){
            customer.setSname(employeeService.getById(customer.getSaleId()).getName());
            if (employeeService.getById(customer.getOperatorId())!=null){
                customer.setOperatorName(employeeService.getById(customer.getOperatorId()).getName());
            }

        }

        //返回查询到的数据
        return R.ok().data("items",customers).data("total",page1.getTotal());
    }

    /**
     * 保存数据
     * @param customer
     * @return
     */
    @PostMapping("save")
    public R save(@RequestBody String customer)  {
        Customer customer1 =JSON.parseObject(customer,Customer.class);
        System.out.println(customer1);
        this.fileList = customer1.getFileList();
        customer1.setDate(new Date());
        if (service.save(customer1)){
            for (String url:fileList){
                String[] ss = url.split("yyx_images_customer/");
                customerImgService.save(new CustomerImg(ss[1],customer1.getCid(),url));
            }
            return R.ok();
        }
        return R.error();
    }

    /**
     * 根据id删除数据
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R remove(@PathVariable String id) {
        service.removeById(id);
        return R.ok();
    }

    /**
     * 更新
     * @param customer
     * @return
     */
    @PostMapping("update")
    public R update(@RequestBody Customer customer) {
        List<String> urls = customer.getFileList();
        for (String url:urls){
            customerImgService.save(new CustomerImg((UUID.randomUUID()).toString(),customer.getCid(),url));
        }
        customer.setGmtModified(new Date());
        service.updateById(customer);

        return R.ok();
    }

    /**
     * 根据id获取数据
     * @param id
     * @return
     */
    @GetMapping("get/{id}")
    public R get(@PathVariable String id) {
        System.out.println();
        Customer customer = service.getById(id);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("cid",customer.getCid());
        List<CustomerImg> list = customerImgService.list(queryWrapper);
        List list1 = new ArrayList<>();
        for (CustomerImg c:list){
            if (c!=null) {
                list1.add(c.getImg());
            }
        }
        customer.setFileList(list1);

        return R.ok().data("item", customer);
    }

    /**
     * 删除图片
     * @param fileName
     * @return
     */
    @DeleteMapping("deletePicture/{fileName}")
    public R deleteimg(@PathVariable String fileName){
        customerImgService.removeById(fileName);
        OssUtil.deleteFile(OssUtil.OSS_CLIENT,OssUtil.BUCKET_NAME,OssUtil.FOLDER,fileName);
        return R.ok();
    }
    @GetMapping("getCoustomerByPhone/{phone}")
    public R getByPhone(@PathVariable String phone){
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone);
            Customer customer = service.getOne(queryWrapper);
            if (customer!=null) {
                return R.ok().data("customer", customer);
            }else {
                return R.error().message("没有找到与该电话号码匹配的客户");
            }

    }
}

